package org.jiucheng.magpiebridge.manager.controller.openapi.v1;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.jiucheng.ioc.annotation.Inject;
import org.jiucheng.magpiebridge.manager.dto.openapi.v1.ClientReqDto;
import org.jiucheng.magpiebridge.manager.dto.openapi.v1.Openapi;
import org.jiucheng.magpiebridge.manager.entity.Client;
import org.jiucheng.magpiebridge.manager.entity.Server;
import org.jiucheng.magpiebridge.manager.handler.OpenapiHandler;
import org.jiucheng.magpiebridge.manager.handler.RequestBody;
import org.jiucheng.magpiebridge.manager.out.OpenapiOut;
import org.jiucheng.magpiebridge.manager.service.IClientService;
import org.jiucheng.magpiebridge.manager.util.MD5Util;
import org.jiucheng.magpiebridge.manager.util.ServerNotify;
import org.jiucheng.magpiebridge.manager.util.ThreadArgs;
import org.jiucheng.plugin.db.IBaseService;
import org.jiucheng.util.StringUtil;
import org.jiucheng.web.annotation.Controller;
import org.jiucheng.web.annotation.RequestMapping;
import org.jiucheng.web.annotation.RequestMethod;

@Controller(OpenapiHandler.class)
public class ClientController {
    
    @Inject
    private IBaseService baseService;
    @Inject
    private IClientService clientService;
    
    @RequestMapping(value = "/openapi/v1/client/token/change", method = RequestMethod.POST, out = OpenapiOut.class)
    public Openapi tokenChange(@RequestBody ClientReqDto reqDto) {
        if (reqDto == null) 
            return Openapi.newInstance(1, "请求内容不能为空");
        if (reqDto.getId() == null)
            return Openapi.newInstance(2, "编号不能为空");
        Client client = baseService.get(Client.class, reqDto.getId());
        if (client == null)
            return Openapi.newInstance(3, "编号有误");
        if (!client.getUserId().equals(ThreadArgs.getGid()))
            return Openapi.newInstance(4, "非法操作");
        String oldToken = client.getToken();
        
        client.setToken(MD5Util.getMd5(UUID.randomUUID().toString()));
        baseService.update(client);
        
        try {
            Server server = baseService.get(Server.class, client.getServerId());
            if (server != null)
                ServerNotify.notify(server, oldToken);
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return Openapi.newInstance(client.getToken());
    }
    
    @RequestMapping(value = "/openapi/v1/client/edit", method = RequestMethod.POST, out = OpenapiOut.class)
    public Openapi edit(@RequestBody ClientReqDto reqDto) {
        if (reqDto == null) 
            return Openapi.newInstance(1, "请求内容不能为空");
        if (reqDto.getId() == null)
            return Openapi.newInstance(2, "编号不能为空");
        if (StringUtil.isBlank(reqDto.getName()))
            return Openapi.newInstance(2, "名称不能为空");
        Client client = baseService.get(Client.class, reqDto.getId());
        if (client == null)
            return Openapi.newInstance(3, "编号有误");
        if (!client.getUserId().equals(ThreadArgs.getGid()))
            return Openapi.newInstance(4, "非法操作");
        client.setName(reqDto.getName());
        baseService.update(client);
        return Openapi.newInstance();
    }
    
    @RequestMapping(value = "/openapi/v1/client/del", method = RequestMethod.POST, out = OpenapiOut.class)
    public Openapi del(@RequestBody ClientReqDto reqDto) {
        if (reqDto == null) 
            return Openapi.newInstance(1, "请求内容不能为空");
        if (StringUtil.isBlank(reqDto.getIds()))
            return Openapi.newInstance(2, "编号不能为空");
        
        String[] idsStr = reqDto.getIds().split(",");
        List<Client> clients = new ArrayList<Client>();
        for (String idStr : idsStr) {
            if (StringUtil.isNotBlank(idStr) && idStr.matches("[0-9]+")) {
                Client client = baseService.get(Client.class, Long.parseLong(idStr));
                if (client != null) {
                    if (!client.getUserId().equals(ThreadArgs.getGid()))
                        return Openapi.newInstance(4, "非法操作");
                    clients.add(client);
                }
            }
        }
        if (!clients.isEmpty()) {
            clientService.deleteClients(clients);
            for (Client client : clients) {
                try {
                    Server server = baseService.get(Server.class, client.getServerId());
                    if (server != null) {
                        ServerNotify.notify(server, client.getToken());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return Openapi.newInstance();
    }
    
    @RequestMapping(value = "/openapi/v1/client/add", method = RequestMethod.POST, out = OpenapiOut.class)
    public Openapi add(@RequestBody ClientReqDto reqDto) {
        if (reqDto == null) 
            return Openapi.newInstance(1, "请求内容不能为空");
        if (StringUtil.isBlank(reqDto.getName()))
            return Openapi.newInstance(2, "名称不能为空");
        if (reqDto.getServerId() == null)
            return Openapi.newInstance(3, "服务器不能为空");
        if (baseService.get(Server.class, reqDto.getServerId()) == null)
            return Openapi.newInstance(4, "服务器不存在");
        Client client = new Client();
        client.setName(reqDto.getName());
        client.setServerId(reqDto.getServerId());
        client.setToken(MD5Util.getMd5(UUID.randomUUID().toString()));
        client.setUserId(ThreadArgs.getGid());
        return Openapi.newInstance(baseService.save(client));
    }
}
